<template>
  <el-dialog
    v-model="visible"
    :title="$t('product.select')"
    top="100px"
    :close-on-click-modal="false"
    :before-close="closeBefore"
    width="960px"
    class="prods-select-dialog component-prods-select"
  >
    <!-- native modifier has been removed, please confirm whether the function has been affected  -->
    <el-form
      :inline="true"
      :model="dataForm"
      class="demo-form-inline"

      @submit.prevent
    >
      <el-form-item :label="$t('product.prodName') + ':'">
        <el-input
          v-model.trim="prodName"
          :placeholder="$t('product.prodName')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('marketing.subHeadings') + ':'">
        <el-cascader
          v-model="selectedCategory"
          expand-trigger="hover"
          :options="categoryList"
          :props="categoryTreeProps"
          :clearable="true"
          @change="handleChange"
        />
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn primary-btn"
          @click="searchProd"
        >
          {{
            $t("order.query")
          }}
        </div>
      </el-form-item>
      <el-form-item>
        <div
          class="default-btn"
          @click="clean"
        >
          {{
            $t("shop.resetMap")
          }}
        </div>
      </el-form-item>
    </el-form>
    <div class="prods-select-body">
      <el-table
        ref="prodTableRef"
        v-loading="dataListLoading"
        :data="dataList"
        :header-cell-style="{height: '42px', background: '#F6F7FA', color:'#666666','font-weight': '500'}"
        :cell-style="{height: '64px', padding: '8px 0', color:'#000'}"
        :row-key="getRowKeys"
        style="width: 100%"
        height="420"
        @selection-change="selectChangeHandle"
        @select="selectHandle"
        @select-all="selectAllHandle"
      >
        <el-table-column
          v-if="isSingle"
          width="50"
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <div class="prods-select-radio">
              <!-- native modifier has been removed, please confirm whether the function has been affected  -->
              <el-radio
                v-model="singleSelectProdId"
                :label="scope.row.prodId"
                @change="getSelectProdRow(scope.row)"
              >
&nbsp;
              </el-radio>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!isSingle"
          type="selection"
          header-align="center"
          align="center"
          width="50"
        />
        <el-table-column
          align="left"
          width="550"
          :label="$t('product.prodInfo')"
        >
          <template #default="scope">
            <div class="prod-info">
              <img
                v-if="scope.row.pic"
                :src="checkFileUrl(scope.row.pic)"
                style="width: 48px;height: 48px;"
                alt
              >
              <img
                v-else
                src="@/assets/img/def.png"
                style="width: 48px;height: 48px;"
                alt
              >
              <span class="prod-name">{{ scope.row.prodName }}</span>
            </div>
          </template>
        </el-table-column>
        <!-- 销售价(元) -->
        <el-table-column
          prop="price"
          :label="$t('product.sellingPrice')"
        >
          <template #default="scope">
            <span class="prod-name">{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="totalStocks"
          :label="$t('product.totalStocks')"
        />
      </el-table>
    </div>
    <el-pagination
      style="margin-top:15px"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
    />
    <template #footer>
      <div>
        <div
          class="default-btn"
          @click="cancelFn"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          class="default-btn primary-btn"
          type="primary"
          @click="submitProds()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { treeDataTranslate, idList } from '@/utils/index.js'
import { ElMessageBox } from 'element-plus'

const props = defineProps({
  isSingle: {
    default: false,
    type: Boolean
  },
  prodType: {
    default: null,
    type: Number
  },
  dataUrl: {
    default: '/prod/prod/page',
    type: String
  },
  giveawayId: {
    default: 0,
    type: [String, Number]
  },
  groupActivityId: {
    default: null,
    type: [String, Number]
  }
})
const emit = defineEmits([
  'refreshSelectProds',
  'refreshSelectProds',
  'refreshSelectProds',
  'refreshSelectProds',
  'closeProdsSelect'
])

const dataForm = reactive({
  product: ''
})
const categoryTreeProps = reactive({
  value: 'categoryId',
  label: $t('language') === 'English' ? 'categoryNameEn' : 'categoryName'
})

onActivated(() => {
  getDataList()
})

const prodTableRef = ref(null)
onBeforeUnmount(() => {
  prodTableRef.value?.clearSelection()
})

const singleSelectProdId = ref(0)
const visible = ref(false)
const dataListLoading = ref(false)
let dataListSelections = []
// 获取数据列表
const init = (selectProds) => {
  singleSelectProdId.value = 0
  selectProds = selectProds || []
  visible.value = true
  dataListLoading.value = true
  if (selectProds) {
    selectProds.forEach(row => {
      dataListSelections.push(row)
    })
  }
  getDataList()
  getCategoryList()
}

const categoryList = ref([])
const getCategoryList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams({
      status: 1
    })
  }).then(({ data }) => {
    categoryList.value = treeDataTranslate(data, 'categoryId', 'parentId')
  })
}

const cancelFn = () => {
  clean()
  visible.value = false
  prodTableRef.value?.clearSelection()
}

const pageIndex = ref(1)
const pageSize = ref(10)
const totalPage = ref(0)
const prodName = ref('')
let shopCategoryId = null
const dataList = ref([])
const getDataList = () => {
  http({
    url: http.adornUrl(props.dataUrl),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageIndex.value,
          size: pageSize.value,
          prodName: prodName.value ? prodName.value : null,
          prodType: props.prodType,
          shopCategoryId: shopCategoryId || null,
          status: 1,
          giveawayId: props.giveawayId ? props.giveawayId : null,
          groupActivityId: props.groupActivityId ? props.groupActivityId : null,
          isActive: 1 // 过滤掉活动商品
        }
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    totalPage.value = data.total
    dataListLoading.value = false
    if (dataListSelections.length) {
      nextTick(() => {
        dataListSelections.forEach(row => {
          const index = dataList.value.findIndex((prodItem) => prodItem.prodId === row.prodId)
          if (index >= 0) {
            prodTableRef.value.toggleRowSelection(dataList.value[index], true)
          }
        })
      })
    }
  })
}

// 每页数
const sizeChangeHandle = (val) => {
  pageSize.value = val
  pageIndex.value = 1
  getDataList()
}

// 当前页
const currentChangeHandle = (val) => {
  pageIndex.value = val
  getDataList()
}

// 单选商品事件
const getSelectProdRow = (row) => {
  dataListSelections = [row]
}

const selectAllHandle = (e) => {
  if (e.length > 0) {
    dataListSelections = dataListSelections.filter(value => dataList.value.map(val => val.prodId).indexOf(value.prodId) === -1)
    dataList.value.forEach(value => {
      dataListSelections.push(value)
    })
  } else {
    dataListSelections = dataListSelections.filter(value => dataList.value.map(val => val.prodId).indexOf(value.prodId) === -1)
  }
}

// 多选点击事件
const selectHandle = (selection, row) => {
  // 判断是否选中
  const selectionStatu = selection.map(element => element.prodId).indexOf(row.prodId) !== -1
  if (selectionStatu && selection.length > 0 && selection) {
    // 选中添加
    dataListSelections.push(row)
  } else {
    // 未选中删除
    dataListSelections = dataListSelections.filter(element => element.prodId !== row.prodId)
  }
}

// 多选事件
const selectChangeHandle = () => {}

const getRowKeys = (row) => {
  return row.prodId
}

/**
 * 获取分类id
 */
const handleChange = (val) => {
  shopCategoryId = val[val.length - 1]
}

/**
 * 根据条件搜索商品
 */
const searchProd = () => {
  pageIndex.value = 1
  getDataList()
}

const selectedCategory = ref([])
/**
 * 清空搜索条件
 */
const clean = () => {
  prodName.value = ''
  shopCategoryId = null
  selectedCategory.value = idList(categoryList.value, shopCategoryId, 'categoryId', 'children').reverse()
}

// 确定事件
const submitProds = () => {
  // 商品单选情况
  if (props.isSingle) {
    dataListSelections.length && emit('refreshSelectProds', dataListSelections[0])
    dataListSelections = []
    visible.value = false
    // 商品多选情况
  } else {
    const prods = []
    dataListSelections.forEach(item => {
      const prodIndex = prods.findIndex((prod) => prod.prodId === item.prodId)
      if (prodIndex === -1) {
        prods.push(
          {
            prodId: item.prodId,
            prodName: item.prodName,
            pic: checkFileUrl(item.pic),
            activityId: item.activityId,
            prodType: item.prodType,
            oriPrice: item.oriPrice,
            price: item.price,
            brief: item.brief,
            activityPrice: item.activityPrice
          }
        )
      }
    })
    let msgInfo = ''
    // 秒杀活动选择商品的提示
    if (props.dataUrl.includes('canSekcillProdPage')) {
      msgInfo = $t('components.seckillWhetherToContinue')
    } else if (props.dataUrl.includes('getNotGroupProdPage')) {
      // 拼团活动选择商品的提示
      msgInfo = $t('components.groupWhetherToContinue')
    }
    if (msgInfo !== '' && msgInfo !== null) {
      prodIsSeckill(prods, msgInfo)
    } else {
      emit('refreshSelectProds', prods)
      dataListSelections = []
      visible.value = false
    }
  }
}

/**
 * 查询商品是否在参与秒杀活动
 */
const prodIsSeckill = (prods, msgInfo) => {
  const prodIds = []
  for (let index = 0; index < prods.length; index++) {
    prodIds.push(prods[index].prodId)
  }
  http({
    url: http.adornUrl('/admin/discount/prodIsDiscount'),
    method: 'post',
    data: prodIds
  }).then(({ data }) => {
    const msg = data
    if (msg !== undefined && msg !== null && msg !== '') {
      ElMessageBox.confirm(msgInfo, $t('text.tips'), {
        confirmButtonText: $t('crud.filter.submitBtn'),
        cancelButtonText: $t('crud.filter.cancelBtn'),
        type: 'warning'
      }).then(() => {
        emit('refreshSelectProds', prods)
        dataListSelections = []
        visible.value = false
      }).catch(() => {})
    } else {
      emit('refreshSelectProds', prods)
      dataListSelections = []
      visible.value = false
    }
  })
}

/**
 * 关闭前操作
 */
const closeBefore = (done) => {
  clean()
  emit('closeProdsSelect')
  visible.value = false
  done()
}

defineExpose({
  init
})

</script>
<style lang="scss" scoped>
@use "index";
</style>
